package com.core.sgip.client;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.apache.log4j.Logger;

import com.core.sgip.common.SGIPConstant;
import com.core.sgip.common.SGIPMsg;
import com.core.sgip.common.SGIPproperties;
import com.core.sgip.common.body.command.BindResp;
import com.core.sgip.common.body.command.Submit;
import com.core.sgip.common.body.command.SubmitResp;
import com.core.sgip.common.factory.SGIP2UpFactory;
import com.core.sgip.interf.SGIPmessageHandler;
import com.demo.jfinal.model.ApiOrders;

public class SGIP2UpClient {

	private static Logger logger = Logger.getLogger(SGIP2UpClient.class);

	private static SGIPmessageHandler sGIPmessageHandler = SGIPproperties.SGIP_MSG_HANDLER;

	/**
	 * 发送消息
	 * 
	 * @param listUserNumber
	 * @param content
	 * @throws Exception
	 */
	public static void sendMsg(String appkey, String securtykey, String sgipip, String sgipport,
			List<String> listUserNumber, String content,ApiOrders apiOrders) throws Exception {
		if (null == listUserNumber || 0 == listUserNumber.size() || null == content || 0 == content.length()) {
			return;
		}
		// 验证号码是否前面有86
		for (int i = 0; i < listUserNumber.size(); i++) {
			String un = listUserNumber.get(i);
			if (!un.startsWith("86")) {
				listUserNumber.set(i, "86" + un);
			}
		}
		startCommunication(appkey, securtykey, sgipip, sgipport, listUserNumber, content,apiOrders);
	}

	private static void startCommunication(String appkey, String securtykey, String sgipip, String sgipport,
			List<String> listUserNumber, String content,ApiOrders apiOrders) throws Exception {
		logger.info("上行：param{} sgiipip = "+sgipip +",sgipport  = "+sgipport+",appkey = "+appkey+",securtykey = "+securtykey+",listUserNum.get(0) = "+listUserNumber.get(0)+",content  = "+content);
		Socket socket = null;
		InputStream is = null;
		OutputStream os = null;
		try {
			// logger.debug("*********start build socket=" +
			// SGIPproperties.SERVER_IP + ":" + SGIPproperties.SERVER_PORT);
			// socket = new Socket("120.25.209.225", Integer.valueOf("8801"));
			// socket = new Socket("112.21.182.33", Integer.valueOf("7890"));

			/**
			 * 上游提供的sgip服务
			 */
			socket = new Socket(sgipip, Integer.valueOf(sgipport));
			// socket = new Socket("123.59.105.237", Integer.valueOf("38001"));
			logger.debug("********* builded socket=" + socket);
			socket.setKeepAlive(true);
			os = socket.getOutputStream();
			is = socket.getInputStream();
			// 发送bind
			logger.debug("*********send bind start*********");
			SGIPMsg msg = SGIP2UpFactory.getSGIPMsg2(appkey, securtykey, SGIPConstant.SGIP_BIND);
			byte[] dataByte = msg.getByteData();
			os.write(dataByte);
			os.flush();

			logger.debug("*********send bind end and start receive bindResp*********");
			// 接受bindResp
			SGIPMsg returnMsg = SGIP2UpFactory.constructSGIPMsg(getAvailableBytes(is));
			logger.debug("*********end receive bindResp*********returnMsg=" + returnMsg);
			if (returnMsg != null && returnMsg.getHead() != null
					&& returnMsg.getHead().getCommandId() == SGIPConstant.SGIP_BIND_RESP) {
				BindResp br = (BindResp) returnMsg.getCommand();
				if (null != br) {
					int result = br.getResult();
					logger.debug("****************** bindResp's result:	" + result);
					if (0 != result) {
						String errorMsg = SGIPConstant.ERROR_CODE.get(result + "");
						logger.error("错误消息:" + errorMsg);
						throw new Exception(errorMsg);
					} else {
						int size = listUserNumber.size();
						int multi = 1;
						int fromIndex = 0;
						int toIndex = size;
						if (size > SGIPproperties.SGIP_SUBMIT_MAX_USER_NUMBER) {
							multi = size / SGIPproperties.SGIP_SUBMIT_MAX_USER_NUMBER
									+ (size % SGIPproperties.SGIP_SUBMIT_MAX_USER_NUMBER > 0 ? 1 : 0);
						}
						boolean sendSubmitOver = false;
						for (int i = 0; i < multi; i++) {
							toIndex = fromIndex + SGIPproperties.SGIP_SUBMIT_MAX_USER_NUMBER;
							toIndex = toIndex > size ? size : toIndex;
							List<String> tempUserNumbers = listUserNumber.subList(fromIndex, toIndex);
							fromIndex = (i + 1) * SGIPproperties.SGIP_SUBMIT_MAX_USER_NUMBER;
							// bind成功 发送Submit
							logger.debug("*********bind success start send submit*******listNumberSize:"
									+ tempUserNumbers.size());
							
							msg = SGIP2UpFactory.getSGIPMsg(SGIPConstant.SGIP_SUBMIT);
							
							logger.info("sequenceNumber1 = "+msg.getHead().getSequenceNumberStr());
							
							msg.setUserNumbers(tempUserNumbers, content);
							
							dataByte = msg.getByteData();
							
							// 处理Submit(把当前数据放到sms_gateway_interface表)
							sGIPmessageHandler.handleSubmitMessage2UpJob(msg.getHead(), (Submit) msg.getCommand(),apiOrders);
							
							System.out.println("sequenceNumber2 = "+msg.getHead().getSequenceNumberStr());
							
							os.write(dataByte);
							os.flush();

							logger.debug("*********end send submit start receive submitResp*********");
							returnMsg = SGIP2UpFactory.constructSGIPMsg(getAvailableBytes(is));
							logger.debug("************returnMsg=" + returnMsg);
							if (returnMsg != null && returnMsg.getHead() != null
									&& returnMsg.getHead().getCommandId() == SGIPConstant.SGIP_SUBMIT_RESP) {
								SubmitResp sr = (SubmitResp) returnMsg.getCommand();
								if (null != sr) {
									result = sr.getResult();
									logger.debug("****************** submitResp's result:	" + result);
									if (0 != result) {
										String errorMsg = SGIPConstant.ERROR_CODE.get(result + "");
										logger.error("错误消息:" + errorMsg);
										throw new Exception(errorMsg);
									} else {
										logger.debug("*********submit success *********");
									}
								}
							}

							if ((i + 1) == multi) {
								sendSubmitOver = true;
							}
						}
						if (sendSubmitOver) {
							// 发送UnBind
							logger.debug("*********submit all send success start send Unbind *********");
							{
								msg = SGIP2UpFactory.getSGIPMsg(SGIPConstant.SGIP_UNBIND);
								dataByte = msg.getByteData();
								os.write(dataByte);
								os.flush();
								logger.debug("*********end send Unbind start receive UnbindResp*********");
								returnMsg = SGIP2UpFactory.constructSGIPMsg(getAvailableBytes(is));
								logger.debug("************returnMsg=" + returnMsg);
								if (returnMsg != null && returnMsg.getHead() != null
										&& returnMsg.getHead().getCommandId() == SGIPConstant.SGIP_UNBIND_RESP) {
									logger.debug("*********Unbind success *********");
								}
							}
						}
					}
				}
			}
		} catch (Exception e) {
			logger.error("socket 请求异常：信息"+e);
			e.printStackTrace();
			throw new Exception(e.getMessage());
		} finally {
			if (os != null) {
				try {
					os.close();
				} catch (IOException e) {
					logger.error("Error", e);
				}
			}
			if (is != null) {
				try {
					is.close();
				} catch (IOException e) {
					logger.error("Error", e);
				}
			}
			if (null != socket) {
				logger.debug("*********release socket=" + sgipip+ ":" + sgipport);
				try {
					socket.close();
				} catch (IOException e) {
					logger.error("Error", e);
				}
			}
		}
	}

	public static byte[] getAvailableBytes(InputStream inputStream) throws Exception {
		Calendar cal = Calendar.getInstance();
		long startMillis = cal.getTimeInMillis();
		long endMillis = startMillis;
		int timeout = 5;

		int count = 0;
		while (count == 0) {
			endMillis = Calendar.getInstance().getTimeInMillis();
			count = inputStream.available();
		}
		// if (count == 0 && (endMillis - startMillis) > timeout * 1000) {
		// throw new Exception("read server response time out !");
		// }
		byte[] bytes = new byte[count];
		int readCount = 0; // 已经成功读取的字节的个数
		while (readCount < count) {
			readCount += inputStream.read(bytes, readCount, count - readCount);
		}
		return bytes;
	}

	public static void main(String[] args) throws Exception {
		List<String> listUserNumber = new ArrayList<String>();
		listUserNumber.add("13246864965");
//		 sendMsg("07007","abc07007!@#","121.31.255.203","8803",listUserNumber, "加班使我感到快乐~",Long.valueOf("518100000"));
		ApiOrders api = new ApiOrders();
		api.set("ORDER_ID","1705191041");
		api.set("PHONE_NO","13246864966");
		api.set("GATEWAY_ID","123456");
		api.set("SEND_DATE",new Date());

		
//		 sendMsg("101726","@2017*&^","192.168.0.110","58802",listUserNumber, "【云之讯】郭星1700退订回复T", Long.valueOf("519103912"), null);
		
		//广西联通
		 sendMsg("07007","abc07007!@#","120.25.209.225","58802",listUserNumber, "【云之讯】郭星05241353退订回复T", api);
//		 sendMsg("07007","abc07007!@#","121.31.255.203","8803",listUserNumber, "加班使我感到快乐05241015", Long.valueOf("519103912"), null);
	}

}